package model

import (
	"errors"
	"haodayizhi/global"

	"gorm.io/gorm"
)

const TableNamePermission = "permissions"

// Permission mapped from table <permissions>
type Permission struct {
	ID          int64  `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id,string"`
	Name        string `gorm:"column:name;type:varchar(255)" json:"name"`
	Description string `gorm:"column:description;type:text" json:"description"`
	Action      string `gorm:"column:action;type:enum('create','read','update','delete')" json:"action"`
}

// TableName Permission's table name
func (*Permission) TableName() string {
	return TableNamePermission
}

// CreatePermission creates a new Permission in the database.
func (m *Permission) CreatePermission() error {
	if err := global.Db.Create(m).Error; err != nil {
		return err
	}
	return nil
}

// GetPermissionByID retrieves a Permission by its ID from the database.
func (m *Permission) GetPermissionByID(id int64) (*Permission, error) {
	result := global.Db.First(m, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // Permission not found
		}
		return nil, result.Error
	}
	return m, nil
}

// UpdatePermission updates an existing Permission in the database.
func (m *Permission) UpdatePermission() error {
	if err := global.Db.Save(m).Error; err != nil {
		return err
	}
	return nil
}

// DeletePermission deletes a Permission by its ID from the database.
func (m *Permission) DeletePermission(id int64) error {
	if err := global.Db.Delete(m, id).Error; err != nil {
		return err
	}
	return nil
}
